#!/bin/bash

# 执行后确保用Hugo生成的站点可以正常渲染，特别是数学公式。
# 先将`$$`
# 转换成`{{</* katex [display] */>}}latex{{</* /katex */>}}`
# 再执行 hugo [servere] -D 命令
# ./forgitee       # 站点发布（生成静态文件）
# ./forgitee server  # 站点预览

function action(){
    for file in `ls $1` 
    do
        if [ -d $1"/"$file ] 
        then
            action $1"/"$file
        elif [ "${file#*.}"x = "md"x ]
        then
            # 方便发布到gitee
            # 1）跳过行内代码: ```online code```
            # 2）跳过行间代码:
            # ```
            # multiline code
            # ``` 
            # 3）多行公式变换:
            # $$
            # multiline latex
            # $$ 
            # 4）行内公式变换: $$online latex$$
            # 5）行内公式变换: $online latex$
            # 6）图片链接变换
            sed -i '/```[^`]*```/n; /^```/ { :begin1; /^```.*\s*\n\s*```/! { $! { N; b begin1 }; }; n; }; /\$\$/ { :begin2; /\$\$[^$]*\$\$/! { $! { N; b begin2 }; }; }; s/\$\$\(\n[^$]*\n\)\$\$/{{< katex display >}}\1{{< \/katex >}}/g; s/\$\$\([^$]*\)\$\$/{{< katex >}}\1{{< \/katex >}}/g; s/\$\([^$]*\)\$/{{< katex >}}\1{{< \/katex >}}/g; s/\[\[\([^[]*\)|\([^[]*\)\]\]/[\2]({{< roamlink "\1" >}})/g; s/\[\[\([^[|]*\)\]\]/[\1]({{< roamlink "\1" >}})/g; '  $1"/"$file
        fi
    done
}

if [ -d "./content" ]
then

    if [ "$1"x = "server"x ] 
    then
        # 私有数据备份
        rm -rd ../private
        rm -rd ../.obsidian
        mv ./content/private ../
        mv ./content/.obsidian ../
    fi

    echo "确保站点可解析,转换中..."
    action ./content
    echo "确保站点可解析,转换完成！"

    if [ "$1"x = "server"x ] 
    then
        hugo server --disableFastRender -D
    else
        rm -rf public
        hugo -D
    fi

    # 复原
    ./fortypora

    if [ "$1"x = "server"x ] 
    then
        # 私有数据复位
        mv ../private ./content/ 
        mv ../.obsidian ./content/
    fi
else
    echo "此脚本只能在包含content的目录notes中执行"    
fi

